import * as alarmService from '../../services/alarm/alarm';

export default {
  namespace: 'alarm',
  state: {
    typeList : [],
    alarmList : [],
    currentItem : {},
    current : 1,
    currentSize : 10,
    total : 0, 
    modalVisible : false,
    modalType : 'handle',
    newKey : '',
  },
  reducers: {
    qryTypesSuc(state, { payload: typeList }) {
      return { ...state, typeList };
    },
    qryAlarmByParamsSuc(state, { payload }) {
      return { ...state, ...payload };
    },
    showModal (state, { payload }) {
      return { ...state, ...payload, newKey : new Date().getTime() + '' , modalVisible: true }
    },
    hideModal (state) {
      return { ...state, modalVisible: false, newKey : new Date().getTime() + '' }
    },
  },
  effects: {
    *qryTypes({ payload },{ call, put }) {    
      const { body }  = yield call(alarmService.qryTypes);
      yield put({ type: 'qryTypesSuc', payload: body.data });
    }, 
    *qryAlarmByParams({ payload },{ call, put }) {
      const { body } = yield call(alarmService.qryAlarmByParams,payload);
      yield put({ type: 'qryAlarmByParamsSuc', payload: { alarmList:body.data, current:body.current, currentSize:body.size, total:body.iTotalRecords }});
    },
    *handleById( { payload },{ call, put }){
      yield put({ type: 'showModal', payload: { currentItem : { id_: payload }, modalType: 'handle' }});
    },
    *viewById( { payload },{ call, put }){
      const { body } = yield call(alarmService.getAlarmResultById,payload);
      yield put({ type: 'showModal', payload: { currentItem : body.data, modalType: 'view' }});
    },
    *handle({ payload,search },{ call, put }){
      const { body } = yield call(alarmService.handle,payload);
      yield put({ type: 'hideModal' });
      yield put({ type: 'qryAlarmByParams',payload:search });
    },
  
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/alarm') {
          dispatch({ type: 'qryTypes' });
          dispatch({ type: 'qryAlarmByParams', payload:{}});
        }
      });
    },
  },
};
